package io.gitee.hechenl.fastiotreport.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.gitee.hechenl.fastiotreport.domain.model.ConfigMetric;
import io.gitee.hechenl.fastiotreport.mapper.ConfigMetricMapper;
import io.gitee.hechenl.fastiotreport.service.IConfigMetricService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ConfigMetricServiceImpl implements IConfigMetricService {

    @Autowired
    private ConfigMetricMapper configMetricMapper;

    @Override
    public List<ConfigMetric> list() {
        return configMetricMapper.selectList(null);
    }

    @Override
    public List<ConfigMetric> list(List<Long> metricIds) {
        return configMetricMapper.selectBatchIds(metricIds);
    }

    @Override
    public List<String> metricGroupList() {
        LambdaQueryWrapper<ConfigMetric> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(ConfigMetric::getMetricGroup).groupBy(ConfigMetric::getMetricGroup);

        List<ConfigMetric> configMetrics = configMetricMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(configMetrics)) {
            return Collections.emptyList();
        }
        return configMetrics.stream().map(
                ConfigMetric::getMetricGroup).collect(Collectors.toList());
    }

    @Override
    public void insertOrUpdate(ConfigMetric configMetric) {
        if (configMetric.getId() != null) {
            LambdaUpdateWrapper<ConfigMetric> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(ConfigMetric::getId, configMetric.getId())
                    .set(ConfigMetric::getMetricGroup, configMetric.getMetricGroup())
                    .set(ConfigMetric::getMetricName, configMetric.getMetricName())
                    .set(ConfigMetric::getMetricExpr, configMetric.getMetricExpr())
                    .set(ConfigMetric::getMetricExprComment, configMetric.getMetricExprComment())
                    .set(ConfigMetric::getMetricExprCal, configMetric.getMetricExprCal());
            configMetricMapper.update(null, wrapper);
        } else {
            configMetricMapper.insert(configMetric);
        }
    }
}